package uk.co.q3c.deplan.server.util.validation;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Deprecated
public class ValidationCheck {
	public static final String CANNOT_BE_NULL = "cannot be null";
	public static final String MUST_BE_GREATER_THAN = "must be greater than ";
	private final List<String> validationMessages;
	private final Map<String, String> fieldValidationMessages;
	private boolean valid;

	public boolean isValid() {
		return valid;
	}

	public void setValid(boolean valid) {
		this.valid = valid;
	}

	/**
	 * Don't want this created externally - use the static factory methods
	 * {@link #newInvalidInstance()} and {@link #newValidInstance()}
	 */
	private ValidationCheck() {
		super();
		fieldValidationMessages = new HashMap<String, String>();
		validationMessages = new ArrayList<String>();
	}

	public String fieldValidationMessage(String fieldName) {
		return fieldValidationMessages.get(fieldName);
	}

	public List<String> validationMessages() {
		return validationMessages;
	}

	public void addValidationMessage(String msg) {
		validationMessages.add(msg);

	}

	public void addfieldValidationMessage(String fieldName, String msg) {
		fieldValidationMessages.put(fieldName, msg);

	}

	/**
	 * returns a new instance with valid set to true
	 */
	public static ValidationCheck newValidInstance() {
		ValidationCheck vob = new ValidationCheck();
		vob.setValid(true);
		return vob;
	}

	// /**
	// * returns a new instance with valid set to false
	// */
	// public static ValidationObject newInvalidInstance() {
	// ValidationObject vob = new ValidationObject();
	// vob.setValid(false);
	// return vob;
	// }

	public String combinedMessages() {
		StringBuilder buf = new StringBuilder("");
		if (validationMessages.size() > 0) {
			buf.append(validationMessages.toString());
		}
		for (Map.Entry<String, String> entry : fieldValidationMessages.entrySet()) {
			buf.append(entry.getKey() + ":" + entry.getValue() + "  ");
		}
		return buf.toString();
	}

	public void checkNotNull(Object object, String fieldName) {
		if (object == null) {
			valid = false;
			fieldValidationMessages.put(fieldName, CANNOT_BE_NULL);
		}

	}

	/**
	 * Null safe checks that the provided collection has greater than
	 * <code>contentSize</code> elements
	 * 
	 * @param collection
	 * @param fieldName
	 * @param collectionSize
	 */
	public void checkCollectionGreaterThan(Collection<?> collection, String fieldName, int collectionSize) {
		if (collection == null) {
			valid = false;
			fieldValidationMessages.put(fieldName, CANNOT_BE_NULL);
			return;
		}
		if (!(collection.size() > collectionSize)) {
			fieldValidationMessages.put(fieldName, MUST_BE_GREATER_THAN + Integer.toString(collectionSize));
			valid = false;
		}
	}

	public boolean isNotValid() {

		return !valid;
	}
}
